package com.sdgs.app.page;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 * 
 * @ClassName: Page
 * @Description: 分页实体
 * 
 * @param <T>
 */
public class Page<T> implements Serializable, Iterable<T> {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	// 结果List
    protected List<T> result;
    // 一页显示的数据量
    protected int pageSize;
    // 总条数
    protected int totalCount = 0;
    // 总页数
    protected int pageCount =1;
    // 当前页
    protected int curPage = 0;
    // 页面显示的 分页数码个数
    protected int pageShowNum = 4;
    protected List<Integer> pageList = new ArrayList<Integer>();

    public Page(PageRequest<T> p, int totalCount) {
        this(p.getPageSize(), totalCount);
    }
    public Page(int pageSize, int totalCount) {
        this(pageSize, totalCount, new ArrayList<T>(0));
    }

    public Page( int pageSize, int totalCount, List<T> result) {
        if (pageSize <= 0) {
            throw new IllegalArgumentException("[pageSize] must great than zero");
        }
        this.pageSize = pageSize;
        this.pageCount = totalCount%pageSize==0?totalCount/pageSize:totalCount/pageSize+1;
        this.totalCount = totalCount;
        setResult(result);
    }

    public void setResult(List<T> elements) {
        if (elements == null) {
            throw new IllegalArgumentException("'result' must be not null");
        }
        this.result = elements;
    }

    public List<T> getResult() {
        return this.result;
    }
    public int getTotalCount() {
        return this.totalCount;
    }


    public int getPageSize() {
        return this.pageSize;
    }

    @SuppressWarnings("unchecked")
	public Iterator<T> iterator() {
        return (Iterator<T>) (this.result == null ? Collections.emptyList().iterator() : this.result.iterator());
    }

	public int getPageCount() {
		return pageCount;
	}

	public void setPageCount(int pageCount) {
		this.pageCount = pageCount;
	}

	public int getCurPage() {
		return curPage;
	}

	public void setCurPage(int curPage) {
		this.curPage = curPage;
	}

	public List<Integer> getPageList() {
		return pageList;
	}

	public void setPageList(List<Integer> pageList) {
		this.pageList = pageList;
	}
	
    public int getPageShowNum() {
		return pageShowNum;
	}

	public void setPageShowNum(int pageShowNum) {
		this.pageShowNum = pageShowNum;
	}

	public void createPageList(){
		int start = 0;
		if(this.curPage<=1*this.pageShowNum){
			start = 1;
		}else if(this.curPage<=2*this.pageShowNum){
			start = this.pageShowNum+1;
		}else{
			start = (this.curPage/this.pageShowNum-1)*this.pageShowNum;
		}
    	 for(int i= start; i<= (this.curPage%this.pageShowNum ==0 ?this.curPage:(this.curPage/this.pageShowNum+1)*this.pageShowNum);i++){
		 	if(i>this.pageCount){
		 		break;
		 	}
		 	pageList.add(i);
		 }
    }
}